package com.example.springstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springstudy.dao.dto.RoleDto;
import com.example.springstudy.entity.Role;
import com.example.springstudy.mapper.RoleMapper;
import com.example.springstudy.service.RoleService;
import com.example.springstudy.utils.DateUtils;
import com.example.springstudy.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Role> getRoles(Long userId) {
        return roleMapper.getRoles(userId);
    }

    @Override
    public List<Role> getRoleList() {
        return this.list(new LambdaQueryWrapper<Role>().eq(Role::getIsDeleted, 0));
    }

    @Override
    public boolean addOrUpdateRole(RoleDto roleDto) {
        Role role = new Role(roleDto);
        if(role.getId() == null || role.getId()==0){
            role.setCreateTime(DateUtils.defaultDate());
            role.setCreateBy(SecurityUtils.getUserId());
        } else {
            role.setUpdateTime(DateUtils.defaultDate());
            role.setUpdateBy(SecurityUtils.getUserId());
        }
        if(!roleDto.getMenuIds().isEmpty()){
            roleMapper.deleteRoleMenus(role.getId());
            roleMapper.saveRoleMenus(role.getId(), roleDto.getMenuIds());
        }
        return this.saveOrUpdate(role);
    }

}
